package org.micropayment.consumer.oauth.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;
import javax.ws.rs.core.Context;
import org.springframework.security.oauth.consumer.OAuthConsumerProcessingFilter;
import org.springframework.security.oauth.consumer.OAuthConsumerSupport;
import org.springframework.security.oauth.consumer.ProtectedResourceDetailsService;
import org.springframework.security.oauth.consumer.token.OAuthConsumerToken;

/**
 *
 * @author jj
 */
@Path("/micropayment/gateway")
@Component
@Scope("request")
public class ConsumerResource {

    private static Logger logger =
        LoggerFactory.getLogger(ConsumerResource.class);

    @Context HttpServletRequest request;
    @Autowired private OAuthConsumerSupport oauthConsumerSupport;
    @Autowired private ProtectedResourceDetailsService resourceDetailsService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String get() {
        OAuthConsumerToken accessToken = null;
        List<OAuthConsumerToken> tokens = (List<OAuthConsumerToken>)
            request.getAttribute(OAuthConsumerProcessingFilter.ACCESS_TOKENS_DEFAULT_ATTRIBUTE);
        if (tokens != null) {
            accessToken = tokens.get(0);
        }
        if (accessToken == null) {
            throw new IllegalArgumentException("Access token not found.");
        }
        //List<String> transactions = getConsumerService().getTransactionIds(token);
        InputStream response = null;
        try {
            response = oauthConsumerSupport.readProtectedResource(new URL(
                    "http://localhost:8080/MicropaymentProvider-1.0-SNAPSHOT/service/oauth/protected"),
                    accessToken, "GET");
        } catch (MalformedURLException ex) {
            logger.error(ex.getMessage(), ex);
        }
        request.getSession().removeAttribute(null);
        return convertStreamToString(response);
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public String commitTransaction() {
        return null;
    }

    public String convertStreamToString(InputStream is) {
        /*
       InputStream is = new FileInputStream( "test.xml" );
       JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
       Unmarshaller u = jc.createUnmarshaller();
       Object o = u.unmarshal( is );
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
            finally {
                try {
                    is.close();
                } catch (IOException ex) {
                    logger.error(ex.getMessage(), ex);
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }

}